package bootload

import (
	"cabinet/model"
	"cabinet/pkg/global"
	log2 "cabinet/pkg/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

// InitDatabase 在中间件中初始化mysql链接

var DB *gorm.DB

func InitDatabase() {
	// 初始化GORM日志配置
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level(这里记得根据需求改一下)
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,       // Disable color
		},
	)
	// 是否开启sql日志
	if global.Conf.Mysql.PrintSql {
		newLogger = newLogger.LogMode(logger.Info)
	} else {
		// not show sql log
		newLogger = newLogger.LogMode(logger.Silent)
	}

	db, err := gorm.Open(mysql.Open(global.Conf.Mysql.Uri), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		Logger:                                   newLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   global.Conf.Mysql.TablePrefix + "_",
			SingularTable: true,
		},
		QueryFields: true,
	})
	// 自动迁移数据库表
	err = db.AutoMigrate(&model.Cabinet{}, &model.CabinetError{}, &model.CabinetMaintenance{}, &model.CabinetRecord{}, &model.StorageRecord{}, &model.CabinetUsage{}, &model.SystemLog{}, &model.OperationLog{}, &model.ErrorLog{})
	if err != nil {
		log.Fatal("Failed to migrate database:", err)
	}
	// Error
	if err != nil {
		log2.Log().Error("mysql lost: %v", err)
		panic(err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		log2.Log().Error("mysql lost: %v", err)
		panic(err)
	}

	//设置连接池
	//空闲
	sqlDB.SetMaxIdleConns(10)
	//打开
	sqlDB.SetMaxOpenConns(20)
	global.Mysql = db
	//migration()
}

//执行数据迁移

//func migration() {
//	// 自动迁移模式
//	_ = global.Mysql.AutoMigrate(&model.Cabinet{})
//}
